<script setup lang="ts">
import { reactive, ref, Ref, onMounted } from "vue"
import { Search, Refresh, Plus } from "@element-plus/icons-vue"
import Table from "@/components/Table/index.vue"
import { propsList } from "./config"
import Modal from "@/components/modal/index.vue"
import { type FormInstance, FormRules, ElMessage } from "element-plus"
import { checkAccount } from "@/utils/index"
import { getRoleListApi, getUserListApi, delUserApi, enableUserApi, addUserApi, editUserApi } from "@/api/system/index"
import { getAreaListApi } from "@/api/architecture/index"
import { resetLoginPwdApi } from "@/api/login/index"
import { type IUserListData } from "@/api/system/types/index"
import { useUserStore } from "@/store/modules/user"
import { storeToRefs } from "pinia"

enum STATUS {
  /** 启用 */
  OPEN = 1,
  /** 停用 */
  DISABLE = 2
}

enum USERROLE {
  ROOT = "root",
  /** 超级管理员 */
  SUPERADMIN = "1",
  /** 普通管理员 */
  ADMIN = "2"
}

interface IFrom {
  page_index: number
  page_size: number
  data_sum: number
  keyword: string
  user_area: number | string
  user_role: number | string
}

interface IOptions {
  label: string
  value: string
}

interface IUserForm {
  /** 用id */
  id?: number
  /** 用户名 **/
  user_name: string
  /** 用户身份id **/
  user_role: string
  /** 角色名称 **/
  role_name?: string
  /** 密码 **/
  user_password: number
  /** 账号 **/
  user_number: string
  /** 分区名称 **/
  area_name?: string
  /** 所属分区id **/
  user_area: string
  /** 手机号 **/
  user_telphone: string
  /** 邮箱 **/
  user_email: string
  /** 备注 **/
  remarks: string
}

const userRule = ref<FormRules<Partial<IUserForm>>>({
  user_name: [{ required: true, message: "请输入姓名" }],
  user_area: [{ required: true, message: "请选择所属分区" }],
  user_role: [{ required: true, message: "请选择角色" }],
  user_number: [
    { required: true, message: "请输入账号" },
    { required: true, validator: checkAccount }
  ]
})

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const isBatch = ref<boolean>(false)
const isEdit = ref<boolean>(false)
const userTitle = ref<string>("添加用户")
const delTitle = ref<string>("删除账号")
const enableTitle = ref<string>("停用账号")
const userFormRef = ref<FormInstance>()
const addUserModalRef: Ref<typeof Modal | null> = ref(null)
const detailModalRef: Ref<typeof Modal | null> = ref(null)
const delUserModalRef: Ref<typeof Modal | null> = ref(null)
const enableUserModalRef: Ref<typeof Modal | null> = ref(null)

const userForm = reactive<IUserForm>({
  user_name: "",
  user_email: "",
  user_password: 123456,
  user_number: "",
  user_area: "",
  user_telphone: "",
  user_role: "",
  remarks: ""
})

const hasSelectData = ref<IUserListData[]>([]) // 选择数据
const tableData = ref<IUserListData[]>([]) // 表格数据
const detailInfo = reactive<Partial<IUserListData>>({}) // 用户详情数据
const selectRoleOptions = ref<IOptions[]>([]) // 角色options
const selectPartitionOptions = ref<IOptions[]>([]) // 分区options
const searchParamsForm = reactive<IFrom>({
  page_index: 1,
  page_size: 10,
  data_sum: 0,
  keyword: "",
  user_area: "",
  user_role: ""
})

const resetData = () => {
  userForm.user_name = ""
  userForm.user_email = ""
  userForm.user_password = 123456
  userForm.user_number = ""
  userForm.user_area = ""
  userForm.user_telphone = ""
  userForm.user_role = ""
  userForm.remarks = ""
  userTitle.value = "添加用户"
}

const handleAddUser = (edit: boolean) => {
  isEdit.value = edit
  if (!edit) {
    resetData()
  }
  ;(addUserModalRef as Ref<typeof Modal>).value.showModal()
}

const handleDetailUser = () => {
  ;(detailModalRef as Ref<typeof Modal>).value.showModal()
}

const handleDelUser = (row: IUserListData) => {
  if (row.id) {
    delTitle.value = "删除账户"
    isBatch.value = false
    Object.assign(detailInfo, row)
  } else {
    delTitle.value = "批量删除账户"
    isBatch.value = true
  }

  ;(delUserModalRef as Ref<typeof Modal>).value.showModal()
}

const handleEnableUser = (row: IUserListData) => {
  if (row.user_status === STATUS.DISABLE) {
    handleEnable(row)
  } else {
    if (row.id) {
      enableTitle.value = "停用账号"
      isBatch.value = false
      Object.assign(detailInfo, row)
    } else {
      enableTitle.value = "批量停用账号"
      isBatch.value = true
    }

    ;(enableUserModalRef as Ref<typeof Modal>).value.showModal()
  }
}

const handleCloseEnable = () => {
  ;(enableUserModalRef as Ref<typeof Modal>).value.closeModal()
}

const handleCloseDetail = () => {
  ;(detailModalRef as Ref<typeof Modal>).value.closeModal()
}

const handleCloseAdd = () => {
  userFormRef.value?.resetFields()
  ;(addUserModalRef as Ref<typeof Modal>).value.closeModal()
}
const handleCloseDel = () => {
  ;(delUserModalRef as Ref<typeof Modal>).value.closeModal()
}

const handleAddConfirm = async () => {
  try {
    const { user_area, user_number, user_name, user_email, user_password, user_role, user_telphone, remarks, id } =
      userForm
    const params: IUserForm = {
      user_telphone,
      user_area,
      user_name,
      user_email,
      user_password,
      user_role,
      remarks,
      user_number
    }

    const regex = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
    const regexPhone = /^1[3|4|5|7|8]\d{9}$/
    const flag = regex.test(user_email)
    const flagPhone = regexPhone.test(user_telphone)

    if (user_email && !flag) return ElMessage.error("请输入正确的邮箱格式")
    if (user_telphone && !flagPhone) return ElMessage.error("请输入正确的手机号格式")

    if (isEdit.value) params.id = id

    const res = isEdit.value ? await editUserApi(params) : await addUserApi(params)
    const { result, return_message } = res
    if (result === 200) {
      ElMessage.success(isEdit.value ? "编辑成功" : "新增成功")
      getUserList()
      handleCloseAdd()
    } else {
      ElMessage.error(return_message)
    }
  } catch (error) {
    console.info(error)
  }
}

const handleSearch = () => {
  searchParamsForm.page_index = 1
  searchParamsForm.page_size = 10
  getUserList()
}

const resetSearch = () => {
  searchParamsForm.keyword = ""
  searchParamsForm.user_area = ""
  searchParamsForm.user_role = ""
  searchParamsForm.page_index = 1
  searchParamsForm.page_size = 10
  getUserList()
}

// 获取用户列表
const getUserList = async () => {
  const { user_area, keyword, user_role, page_size, page_index } = searchParamsForm
  const params = {
    page_size,
    page_index,
    user_area,
    keyword,
    user_role
  }
  const res = await getUserListApi(params)
  const { result, return_message, data } = res
  if (result === 200) {
    tableData.value = data.data
    searchParamsForm.page_index = data.page_index
    searchParamsForm.page_size = data.page_size
    searchParamsForm.data_sum = data.data_sum
  } else {
    ElMessage.error(return_message)
  }
}

// 获取角色options数据
const getRoleList = async () => {
  const res = await getRoleListApi()
  const { data, result, return_message } = res
  if (result === 200) {
    selectRoleOptions.value = data.data.map((item) => {
      return {
        label: item.role_name,
        value: String(item.id)
      }
    })
  } else {
    ElMessage.error(return_message)
  }
}

// 获取分区options数据
const getPartitionList = async () => {
  const params = {
    device_type_id: 1
  }
  const res = await getAreaListApi(params)
  const { data, result, return_message } = res

  if (result === 200) {
    selectPartitionOptions.value = data.data.map((item) => {
      return {
        label: item.area_name,
        value: String(item.id)
      }
    })
  } else {
    ElMessage.error(return_message)
  }
}

// 单个禁启用
const handleEnable = async (row: Partial<IUserListData>) => {
  const params = {
    ids: row.id as number,
    user_status: row.user_status === STATUS.DISABLE ? STATUS.OPEN : STATUS.DISABLE
  }

  const res = await enableUserApi(params)
  const { result, return_message } = res

  if (result === 200) {
    ElMessage.success(row.user_status === STATUS.DISABLE ? "启用成功" : "停用成功")
    getUserList()
  } else {
    ElMessage.error(return_message)
  }
}

/**
 * 批量启用禁用
 * @param status 1 启用 2禁用
 */
const handleBatchEnable = async (user_status: number) => {
  try {
    const ids = hasSelectData.value.map((item) => item.id).toString()
    const params = {
      user_status,
      ids
    }
    const res = await enableUserApi(params)
    const { result, return_message } = res
    if (result === 200) {
      ElMessage.success(STATUS.DISABLE === user_status ? "禁用成功" : "启用成功")
      getUserList()
    } else {
      ElMessage.error(return_message)
    }
  } catch (error) {
    console.info(error)
  }
}

const handleSelect = (selectData: IUserListData[]) => {
  hasSelectData.value = selectData
}

const handleChangePage = (page: number) => {
  searchParamsForm.page_index = page
  getUserList()
}

const handleChangeSize = (size: number) => {
  searchParamsForm.page_size = size
  getUserList()
}

const handleDetail = (row: IUserListData) => {
  Object.assign(detailInfo, row)
  handleDetailUser()
}

const handleEdit = (row: IUserListData) => {
  if (String(row.user_role) === USERROLE.SUPERADMIN) {
    userTitle.value = "编辑管理员信息"
  } else {
    userTitle.value = "编辑用户信息"
  }
  Object.assign(userForm, row)

  console.info(userForm)

  handleAddUser(true)
}

// 重置密码
const resetLoginPwd = async () => {
  try {
    const params = {
      id: userForm.id as number
    }
    const res = await resetLoginPwdApi(params)
    const { result, return_message } = res
    if (result === 200) {
      ElMessage.success("操作成功")
    } else {
      ElMessage.error(return_message)
    }
  } catch (error) {
    console.info(error)
  }
}

// 批量删除
const handleDelBatch = async () => {
  try {
    const params = {
      ids: hasSelectData.value.map((item) => item.id).toString()
    }
    const res = await delUserApi(params)
    const { result, return_message } = res
    if (result === 200) {
      ElMessage.success("删除成功")
      hasSelectData.value = []
      getUserList()
    } else {
      ElMessage.error(return_message)
    }
  } catch (error) {
    console.info(error)
  }
}

// 单个删除
const handleDel = async () => {
  try {
    const params = {
      ids: detailInfo.id as number
    }
    const res = await delUserApi(params)
    const { result, return_message } = res
    if (result === 200) {
      ElMessage.success("删除成功")
      getUserList()
    } else {
      ElMessage.error(return_message)
    }
  } catch (error) {
    console.info(error)
  }
}

// 确认删除
const handleConfirmDel = () => {
  if (isBatch.value) {
    handleDelBatch()
  } else {
    handleDel()
  }
  isBatch.value = false
  handleCloseDel()
}

// 确认停用
const handleConfirmEnable = () => {
  if (isBatch.value) {
    handleBatchEnable(STATUS.DISABLE)
  } else {
    handleEnable(detailInfo)
  }
  isBatch.value = false
  handleCloseEnable()
}

onMounted(() => {
  getRoleList()
  getPartitionList()
  getUserList()
})
</script>
<template>
  <div>
    <!-- 搜索框 -->
    <div flex justify-between bg-white items-center p-15px rounded-5px mb-15px>
      <div flex items-center>
        <el-form ref="searchFormRef" :inline="true" :model="searchParamsForm">
          <el-form-item prop="keyword">
            <el-input v-model="searchParamsForm.keyword" placeholder="请输入账号/姓名" :suffix-icon="Search" />
          </el-form-item>
          <el-form-item prop="user_area">
            <el-select clearable v-model="searchParamsForm.user_area" placeholder="请选择分区" style="width: 240px">
              <el-option
                v-for="item in selectPartitionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item prop="user_role">
            <el-select clearable v-model="searchParamsForm.user_role" placeholder="请选择角色类型" style="width: 240px">
              <el-option v-for="item in selectRoleOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="bg-#387af6!" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button type="primary" :icon="Refresh" class="bg-#387af6!" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div>
        <el-button @click="handleAddUser(false)" type="primary" :icon="Plus" class="bg-#387af6!">添加用户</el-button>
        <el-button
          @click="handleBatchEnable(STATUS.OPEN)"
          :disabled="hasSelectData.length === 0"
          type="primary"
          :class="
            !hasSelectData.length
              ? 'bg-#f5f5f5! border-#d9d9d9! text-#00000040!'
              : 'bg-#fff! text-#2da641! border-#2da641!'
          "
          >批量启用</el-button
        >
        <el-button
          @click="handleEnableUser"
          :disabled="hasSelectData.length === 0"
          type="primary"
          :class="
            !hasSelectData.length
              ? 'bg-#f5f5f5! border-#d9d9d9! text-#00000040!'
              : 'bg-#fff! text-#000000d9! border-#d9d9d9!'
          "
          >批量停用</el-button
        >
        <el-button
          @click="handleDelUser"
          :disabled="hasSelectData.length === 0"
          type="primary"
          :class="
            !hasSelectData.length
              ? 'bg-#f5f5f5! border-#d9d9d9! text-#00000040!'
              : 'bg-#ff7875! text-white! border-#ff7875!'
          "
          >批量删除</el-button
        >
      </div>
    </div>

    <!-- 表格 -->
    <div p-5px bg-white>
      <Table
        :index="true"
        :select-width="60"
        :show-check-box="true"
        header-align="center"
        :total="searchParamsForm.data_sum"
        :data="tableData"
        :propsList="propsList"
        :is-border="true"
        @change-page="handleChangePage"
        @change-size="handleChangeSize"
        @select="handleSelect"
      >
        <template #status="{ row }">
          <div :class="[row.user_status === STATUS.OPEN ? 'text-#70b603' : 'text-#FF4C4C']">
            {{ row.user_status === STATUS.OPEN ? "启用中" : "已停用" }}
          </div>
        </template>

        <template #handler="{ row }">
          <div flex justify-around>
            <span @click="handleDetail(row)" class="text-#387af6!" cursor-pointer>详情</span>
            <span
              v-if="USERROLE.ROOT === userInfo.user_number || row.user_role !== USERROLE.SUPERADMIN"
              @click="handleEdit(row)"
              class="text-#387af6!"
              cursor-pointer
              >编辑</span
            >
            <span
              v-if="USERROLE.SUPERADMIN !== row.user_role || USERROLE.ROOT === userInfo.user_number"
              :class="[row.user_status === STATUS.OPEN ? 'text-#FF4C4C!' : 'text-#70b603']"
              cursor-pointer
              @click="handleEnableUser(row)"
              >{{ row.user_status === STATUS.OPEN ? " 停用" : "启用" }}</span
            >
            <span
              @click="handleDelUser(row)"
              v-if="USERROLE.SUPERADMIN !== row.user_role || USERROLE.ROOT === userInfo.user_number"
              class="text-#FF4C4C!"
              cursor-pointer
              >删除</span
            >
          </div>
        </template>
      </Table>
    </div>

    <!-- 添加编辑用户弹窗 -->
    <Modal ref="addUserModalRef" :title="userTitle" width="720px" @close="handleCloseAdd">
      <template #content>
        <el-form :model="userForm" ref="userFormRef" :rules="userRule" style="max-width: 660px">
          <el-row mb-24px>
            <el-col :span="12">
              <el-form-item label="姓名：" label-width="105px" prop="user_name">
                <el-input clearable placeholder="请输入姓名" v-model="userForm.user_name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号：" label-width="105px" prop="user_number">
                <span v-if="isEdit">{{ userForm.user_number }}</span>
                <el-input v-else placeholder="请输入账号" v-model="userForm.user_number" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="密码：" label-width="105px" prop="user_password">
                <div v-if="isEdit" flex>
                  <el-button @click="resetLoginPwd" class="text-#387af6! border-#387af6!">密码重置</el-button>
                  <span ml-10px>点击重置会恢复默认密码：123456，再次登录时需要修改新密码</span>
                </div>
                <span v-else>默认密码：{{ userForm.user_password }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <div my-25px w-full border-b-1px border-b-solid class="border-b-#e9ebed" />

          <div v-if="!isEdit || USERROLE.SUPERADMIN !== userForm.user_role">
            <el-row mb-24px>
              <el-col :span="12">
                <el-form-item label="所属分区：" label-width="105px" prop="user_area">
                  <el-select clearable v-model="userForm.user_area" placeholder="请选择所属分区" style="width: 240px">
                    <el-option
                      v-for="item in selectPartitionOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="角色：" label-width="105px" prop="user_role">
                  <el-select clearable v-model="userForm.user_role" placeholder="请选择角色" style="width: 240px">
                    <el-option
                      v-for="item in selectRoleOptions.filter((item) => item.value !== '1')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row mb-24px>
              <el-col :span="12">
                <el-form-item label="手机号码：" label-width="105px" prop="user_telphone">
                  <el-input placeholder="请输入手机号" v-model="userForm.user_telphone" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱：" label-width="105px" prop="user_email">
                  <el-input placeholder="请输入邮箱" v-model="userForm.user_email" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注：" label-width="105px" prop="remarks">
                  <el-input
                    placeholder="请输入备注"
                    type="textarea"
                    v-model="userForm.remarks"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div v-else>
            <el-row>
              <el-col :span="12">
                <div flex>
                  <span text-end w-93px>所属分区：</span>
                  <span ml-10px>{{ userForm.area_name }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div flex>
                  <span text-end w-93px>角色：</span>
                  <span ml-12px>{{ userForm.role_name }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </template>

      <template #footer>
        <div pr-20px>
          <el-button class="w-105px!" @click="handleCloseAdd">取消</el-button>
          <el-button class="w-105px! bg-#387af6!" type="primary" @click="handleAddConfirm"> 确定 </el-button>
        </div>
      </template>
    </Modal>

    <!-- 详情弹窗 -->
    <Modal ref="detailModalRef" title="用户详情" width="620px" @close="handleCloseDetail">
      <template #content>
        <div flex flex-col>
          <div h-40px flex items-center border-solid border-1px class="border-#dfe1e3">
            <span pl-15px leading-40px h-full w-100px border-r-solid border-r-1px class="border-r-#dfe1e3">姓名</span>
            <span pl-15px flex-1>{{ detailInfo.user_name ? detailInfo.user_name : "--" }}</span>
          </div>

          <div h-40px flex items-center border-solid border-1px class="border-#dfe1e3">
            <span pl-15px leading-40px h-full w-100px border-r-solid border-r-1px class="border-r-#dfe1e3">账号</span>
            <span pl-15px flex-1>{{ detailInfo.user_number ? detailInfo.user_number : "--" }}</span>
          </div>

          <div h-40px flex items-center border-solid border-1px class="border-#dfe1e3">
            <span pl-15px leading-40px h-full w-100px border-r-solid border-r-1px class="border-r-#dfe1e3"
              >所属分区</span
            >
            <span pl-15px flex-1>{{ detailInfo.area_name }}</span>
          </div>

          <div h-40px flex items-center border-solid border-1px class="border-#dfe1e3">
            <span pl-15px leading-40px h-full w-100px border-r-solid border-r-1px class="border-r-#dfe1e3">角色</span>
            <span pl-15px flex-1>{{ detailInfo.role_name ? detailInfo.role_name : "--" }}</span>
          </div>

          <div h-40px flex items-center border-solid border-1px class="border-#dfe1e3">
            <span pl-15px leading-40px h-full w-100px border-r-solid border-r-1px class="border-r-#dfe1e3"
              >手机号码</span
            >
            <span pl-15px flex-1>{{ detailInfo.user_telphone ? detailInfo.user_telphone : "--" }}</span>
          </div>

          <div h-40px flex items-center border-solid border-1px class="border-#dfe1e3">
            <span pl-15px leading-40px h-full w-100px border-r-solid border-r-1px class="border-r-#dfe1e3">邮箱</span>
            <span pl-15px flex-1>{{ detailInfo.user_email ? detailInfo.user_email : "--" }}</span>
          </div>

          <div h-40px flex items-center border-solid border-1px class="border-#dfe1e3">
            <span pl-15px leading-40px h-full w-100px border-r-solid border-r-1px class="border-r-#dfe1e3">备注</span>
            <span pl-15px flex-1>{{ detailInfo.remarks ? detailInfo.remarks : "--" }}</span>
          </div>
        </div>
      </template>

      <template #footer>
        <div pr-20px>
          <el-button class="w-105px!" @click="handleCloseDetail">关闭</el-button>
        </div>
      </template>
    </Modal>

    <!-- 删除用户 -->
    <Modal ref="delUserModalRef" :title="delTitle" width="520" @close="handleCloseDel">
      <template #content>
        <div flex flex-col>
          <div flex items-center mb-10px>
            <SvgIcon name="warning" class="w-20px! h-20px!" />
            <span ml-5px pl-5px class="bg-#FFFBE6" h-35px leading-40px text-black text-18px>
              确认删除{{ isBatch ? "" : detailInfo.user_name }}账号吗？
            </span>
          </div>
        </div>
      </template>

      <template #footer>
        <div pr-20px>
          <el-button class="w-105px!" @click="handleCloseDel">取消</el-button>
          <el-button class="w-105px! bg-#387af6!" type="primary" @click="handleConfirmDel"> 确定 </el-button>
        </div>
      </template>
    </Modal>

    <!-- 停用用户 -->
    <Modal ref="enableUserModalRef" :title="enableTitle" width="520" @close="handleCloseEnable">
      <template #content>
        <div flex flex-col>
          <div flex items-center mb-10px>
            <SvgIcon name="warning" class="w-20px! h-20px!" />
            <span ml-5px pl-5px class="bg-#FFFBE6" h-35px leading-40px text-black text-18px>
              确认停用{{ isBatch ? "" : detailInfo.user_name }}账号吗？
            </span>
          </div>

          <span ml-25px class="text-#A7A7A8">停用后，所选账号用户将无法登录使用系统</span>
        </div>
      </template>

      <template #footer>
        <div pr-20px>
          <el-button class="w-105px!" @click="handleCloseEnable">取消</el-button>
          <el-button class="w-105px! bg-#387af6!" type="primary" @click="handleConfirmEnable"> 确定 </el-button>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0px;
}

:deep(.el-dialog) {
  background: #f7f9fb;
  padding-left: 0;
  padding-right: 0;
  padding-top: 0;
  border-radius: 5px;

  .el-dialog__body {
    padding: 20px;
  }
}
</style>
